var express = require('express');
var path = require('path');

let app = express();

app.use(express.static(path.join(__dirname, 'public')));
var data = require('./test/test.js');

app.all('*', function (req, resp, next) {
    resp.header("Access-Control-Allow-Origin", "*");
    next();
});

app.get('/user/:id', function (req, resp) {
    var user = Object.assign({}, data.user);
    user.id = req.params.id;
    user.nickName = user.nickName + "_" + req.params.id;
    resp.send(`{"status":0, "message":"Success", "data":${JSON.stringify(user)}}`);
    resp.end();
});

app.get('/driveCard/:uid', function (req, resp) {
    var card = Object.assign({}, data.driveCard);
    card.uid = req.params.uid;
    card.uname = card.uname + "_" + req.params.uid;
    resp.send(`{"status":0, "message":"Success", "data":${JSON.stringify(card)}}`);
    resp.end();
});

app.get('/number/:number', function (req, res) {
    var sid = getCookieNumber(req, res, true);
    var newNumber = req.params.number;
    console.log('syncNumber ' + sid + " = " + newNumber);
    cookieManager[sid] = newNumber;
    res.send(`{"msg":"ok"}`);
    res.end();
});

const cookieManager = {};

function getCookieNumber(req, res, justSid) {
    var ck = req.headers.cookie;
    if (ck) {
        var cks = ck.split(';');
        var sid = 0;
        for (var i = 0; i < cks.length; i++) {
            var pairs = cks[i].split('=');
            if (pairs[0].trim() == 'sid') {
                sid = pairs[1];
            }
        }
    }
    if (justSid) {
        return sid;
    }
    if (sid) {
        if (cookieManager[sid]) {
            console.log('sid = ' + sid);
            return cookieManager[sid];
        }
    } else {
        sid = generateSid();
    }
    console.log('sid = ' + sid);
    cookieManager[sid] = 10000;
    res.cookie('sid', sid);
    return 10000;
}

function generateSid() {
    var tmpId = parseInt(Math.random() * 100000);
    if (cookieManager[tmpId]) {
        return generateSid();
    }
    return tmpId;
}

app.listen(3008);
